﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using PuppeteerSharp;
using YN.WebApi.ResultProcess;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Util.Setvices.Controllers
{
    [Route("[controller]")]
    [IgonreGlobalActionFilter]
    public class OfficeController : Controller
    {

        [HttpPost]
        [Route("loadurl")]
        public async Task<String> loadUrl([FromBody] htmlRequest request)
        {
            if (string.IsNullOrEmpty(request.url))
            {
                throw new ArgumentException("缺少转换的地址", nameof(request));
            }


            // 使用using语句确保资源自动释放
            using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions
            {
                Headless = true,
                ExecutablePath = Environment.GetEnvironmentVariable("PUPPETEER_EXECUTABLE_PATH"),
                Args = new[] { "--no-sandbox", "--disable-gpu" } // 增加额外参数优化
            }))
            {
                using (var page = await browser.NewPageAsync())
                {
                    page.DefaultTimeout = 300 * 1000;
                    await page.GoToAsync(System.Web.HttpUtility.UrlDecode(request.url),
                                       WaitUntilNavigation.Networkidle0);
                }
            } 
            return "加载成功";
        }

        [HttpPost]
        [Route("html2pdf")]
        public async Task<FileResult> GetPDFAsync([FromBody] htmlRequest request)
        {

            var url = request.url;
            if (string.IsNullOrEmpty(url))
            {
                throw new Exception("缺少转换的地址");
            }
            var fileName = request.fileName;
            if (string.IsNullOrEmpty(fileName))
            {
                fileName = $"{Guid.NewGuid().ToString()}.pdf";

            }
            //await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
            var browser = await Puppeteer.LaunchAsync(new LaunchOptions
            {
                Headless = true,
                ExecutablePath = System.Environment.GetEnvironmentVariable("PUPPETEER_EXECUTABLE_PATH"),
                Args = new string[] { "--no-sandbox" },
            });
            var page = await browser.NewPageAsync();

            page.DefaultTimeout = 300 * 1000;
            await page.GoToAsync(System.Web.HttpUtility.UrlDecode(url), WaitUntilNavigation.Networkidle0);

            // 延迟 200 毫秒
            //await Task.Delay(200);

            var pdfBytes = await page.PdfDataAsync(new PdfOptions()
            {
                PrintBackground = false,
                Format = PuppeteerSharp.Media.PaperFormat.A4,
                //Landscape = true

            });

            await browser.DisposeAsync();
            await page.DisposeAsync();
            Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
            return File(pdfBytes, "application/octet-stream;charset=UTF-8", $"{fileName}");


        }

        [HttpPost]
        [Route("html2pdf/background")]
        public async Task<FileResult> GetPDFBackgroundAsync([FromBody] htmlRequest request)
        {

            var url = request.url;
            if (string.IsNullOrEmpty(url))
            {
                throw new Exception("缺少转换的地址");
            }
            var fileName = request.fileName;
            if (string.IsNullOrEmpty(fileName))
            {
                fileName = $"{Guid.NewGuid().ToString()}.pdf";

            }
            //await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
            var browser = await Puppeteer.LaunchAsync(new LaunchOptions
            {
                Headless = true,
                ExecutablePath = System.Environment.GetEnvironmentVariable("PUPPETEER_EXECUTABLE_PATH"),
                Args = new string[] { "--no-sandbox" },
            });
            var page = await browser.NewPageAsync();

            page.DefaultTimeout = 300 * 1000;
            await page.GoToAsync(System.Web.HttpUtility.UrlDecode(url), WaitUntilNavigation.Networkidle0);

            // 延迟 200 毫秒
            //await Task.Delay(1000);

            var pdfBytes = await page.PdfDataAsync(new PdfOptions()
            {
                PrintBackground = true,
                Format = PuppeteerSharp.Media.PaperFormat.A4,
                //Landscape = true

            });

            await browser.DisposeAsync();
            await page.DisposeAsync();
            Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
            return File(pdfBytes, "application/octet-stream;charset=UTF-8", $"{fileName}");


        }

        [HttpPost]
        [Route("html2pdf/background/await")]
        public async Task<FileResult> GetPDFBackgroundAwaitAsync([FromBody] htmlRequest request)
        {

            var url = request.url;
            if (string.IsNullOrEmpty(url))
            {
                throw new Exception("缺少转换的地址");
            }
            var fileName = request.fileName;
            if (string.IsNullOrEmpty(fileName))
            {
                fileName = $"{Guid.NewGuid().ToString()}.pdf";

            }
            //await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
            var browser = await Puppeteer.LaunchAsync(new LaunchOptions
            {
                Headless = true,
                ExecutablePath = System.Environment.GetEnvironmentVariable("PUPPETEER_EXECUTABLE_PATH"),
                Args = new string[] { "--no-sandbox" },
            });
            var page = await browser.NewPageAsync();

            page.DefaultTimeout = 300 * 1000;
            await page.GoToAsync(System.Web.HttpUtility.UrlDecode(url), WaitUntilNavigation.Networkidle0);

            // 延迟 200 毫秒
            await Task.Delay(request.awaitTime);

            var pdfBytes = await page.PdfDataAsync(new PdfOptions()
            {
                PrintBackground = true,
                Format = PuppeteerSharp.Media.PaperFormat.A4,
                //Landscape = true

            });

            await browser.DisposeAsync();
            await page.DisposeAsync();
            Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
            return File(pdfBytes, "application/octet-stream;charset=UTF-8", $"{fileName}");


        }
    }

    
}

public class htmlRequest
    {

        /// <summary>
        /// 地址
        /// </summary>
        public string url { get; set; }

        public string fileName { get; set; }

        public int awaitTime { get; set; }
    }

